﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Speech.Recognition;
using System.Text;
using System.Windows.Forms;

namespace Thenu.SpeechToText
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }
        SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine();
        private void frmMain_Load(object sender, EventArgs e)
        {


            System.Collections.ObjectModel.ReadOnlyCollection<RecognizerInfo> rOnly = SpeechRecognitionEngine.InstalledRecognizers();
            // Create and load a dictation grammar.
            recognizer.LoadGrammar(new DictationGrammar());

            // Add a handler for the speech recognized event.
            recognizer.SpeechRecognized +=
              new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);

            recognizer.RecognizeCompleted +=
         new EventHandler<RecognizeCompletedEventArgs>(recognizer_RecognizeCompleted);

            // Configure input to the speech recognizer.
            //recognizer.SetInputToDefaultAudioDevice();
        }

        private void recognizer_RecognizeCompleted(object sender, RecognizeCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                Console.WriteLine("  Error encountered, {0}: {1}",
                e.Error.GetType().Name, e.Error.Message);
            }
            if (e.Cancelled)
            {
                Console.WriteLine("  Operation cancelled.");
            }
            if (e.InputStreamEnded)
            {
                Console.WriteLine("  End of stream encountered.");
            }
            completed = true;
        }
        public bool completed = false;
        /// <summary>
        /// 识别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            rtbResult.AppendText(Environment.NewLine + e.Result.Text);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                recognizer.SetInputToWaveFile("D:\\2.wma");

                // Start asynchronous, continuous speech recognition.
                recognizer.RecognizeAsync(RecognizeMode.Multiple);
            }
            catch (Exception ex)
            {

            }

        }
    }
}
